<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Flutter测试脚本开发》 - Lucklyの博客 - 在阅读中遇见自己</title><meta name="Description" content="早起的年轻人做的网站"><meta property="og:title" content="《Flutter测试脚本开发》" />
<meta property="og:description" content="
本文主要介绍
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://luckly.work/flutter%E6%B5%8B%E8%AF%95%E8%84%9A%E6%9C%AC%E5%BC%80%E5%8F%91/" />
<meta property="og:image" content="https://luckly.work/logo.png"/>
<meta property="article:published_time" content="2021-07-31T21:37:31+08:00" />
<meta property="article:modified_time" content="2021-07-31T21:37:31+08:00" />
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://luckly.work/logo.png"/>

<meta name="twitter:title" content="《Flutter测试脚本开发》"/>
<meta name="twitter:description" content="
本文主要介绍
"/>
<meta name="application-name" content="LoveIt">
<meta name="apple-mobile-web-app-title" content="LoveIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://luckly.work/flutter%E6%B5%8B%E8%AF%95%E8%84%9A%E6%9C%AC%E5%BC%80%E5%8F%91/" /><link rel="prev" href="https://luckly.work/flutter-engine%E6%BA%90%E7%A0%81%E8%B0%83%E8%AF%95/" /><link rel="next" href="https://luckly.work/flutter%E6%B8%B2%E6%9F%93%E5%8E%9F%E7%90%86%E4%B8%8E%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.13.0/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.7.2/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Flutter测试脚本开发》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/luckly.work\/flutter%E6%B5%8B%E8%AF%95%E8%84%9A%E6%9C%AC%E5%BC%80%E5%8F%91\/"
        },"image": [{
                            "@type": "ImageObject",
                            "url": "https:\/\/luckly.work\/images\/Apple-Devices-Preview.png",
                            "width":  3200 ,
                            "height":  2048 
                        }],"genre": "posts","keywords": "flutter","wordcount":  3239 ,
        "url": "https:\/\/luckly.work\/flutter%E6%B5%8B%E8%AF%95%E8%84%9A%E6%9C%AC%E5%BC%80%E5%8F%91\/","datePublished": "2021-07-31T21:37:31+08:00","dateModified": "2021-07-31T21:37:31+08:00","license": "This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.","publisher": {
            "@type": "Organization",
            "name": "xxxx","logo": {
                    "@type": "ImageObject",
                    "url": "https:\/\/luckly.work\/images\/avatar.png",
                    "width":  528 ,
                    "height":  560 
                }},"author": {
                "@type": "Person",
                "name": "早起的年轻人"
            },"description": ""
    }
    </script></head>
    <body header-desktop="fixed" header-mobile="auto"><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><div class="logo-wrapper">
  <a href="/%20/" class="logo">Lucklyの博客 - 在阅读中遇见自己</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
      <a class="menu-item-link" href="/posts/">所有文章</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/flutter/">Flutter</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/read/">读书笔记</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/go/">Go</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/tags/">标签</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/">分类</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/about/">关于</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="https://github.com/ITmxs">Github</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/friend/">友链</a>
    </li>
  </ul>
</nav><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Flutter测试脚本开发》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>早起的年轻人</a></span>&nbsp;<span class="post-category">收录于 <a href="/categories/flutter/"><i class="far fa-folder fa-fw"></i>Flutter</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-07-31">2021-07-31</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 3239 字&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 7 分钟&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>目录</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li><a href="#单元测试">单元测试</a>
          <ul>
            <li><a href="#导入方式">导入方式</a></li>
            <li><a href="#使用方法">使用方法</a></li>
            <li><a href="#使用说明">使用说明</a></li>
          </ul>
        </li>
        <li><a href="#组件测试">组件测试</a>
          <ul>
            <li><a href="#使用方法-1">使用方法</a></li>
            <li><a href="#使用说明-1">使用说明</a></li>
            <li><a href="#现有问题">现有问题</a></li>
          </ul>
        </li>
        <li><a href="#集成测试">集成测试</a>
          <ul>
            <li><a href="#导入方式-1">导入方式</a></li>
            <li><a href="#使用方法-2">使用方法</a>
              <ul>
                <li><a href="#创建指令化的应用程序">创建指令化的应用程序</a></li>
                <li><a href="#增加测试项">增加测试项</a></li>
                <li><a href="#命令行运行">命令行运行</a></li>
              </ul>
            </li>
            <li><a href="#性能跟踪">性能跟踪</a></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要介绍</p>
</blockquote>
<p>Flutter中支持自动化测试脚本，包括单元测试、组件测试、集成测试等。我们可以使用这些测试方法来验证功能是否正常。</p>
<h2 id="单元测试">单元测试</h2>
<p>Flutter的单元测试实际上就是Dart的单元测试，需要引入相应的库。这里有两种库可供选择：test 或者 flutter_test。其中test库是标准的dart库文件，flutter_test既可用于单元测试也可用于Widget组件测试，推荐使用flutter_test库进行操作。</p>
<h3 id="导入方式">导入方式</h3>
<p>pubspec.yaml 文件中的 <code>dev_dependencies</code>中设置相应依赖：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">dev_dependencies:
  flutter_test:   # 推荐使用这个
    sdk: flutter
#  test: ^1.5.1 这个不推荐
</code></pre></td></tr></table>
</div>
</div><h3 id="使用方法">使用方法</h3>
<p>在test的dart文件中import相应的dart文件，如下面代码所示：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">import &#39;package:flutter_test/flutter_test.dart&#39;; // 使用flutter_test库

//import &#39;package:test/test.dart&#39;;  // 使用test库

void main() {
  test(&#39;my test&#39;, (){
    int i = 0;
    print(&#39;start to check&#39;);
    expect(i, 0);
  });
}
</code></pre></td></tr></table>
</div>
</div><p>在代码中可以看到，有两个方法非常重要：<code>void test(Object description, Function body)</code> 与 <code>expect(dynamic actual, dynamic matcher)</code>，前者是执行的入口，后者进行断言校验。</p>
<p>如果想要执行这个测试脚本，使用Android Studio的话，可以在IDE界面上直接手工操作执行，如下图所示：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/image-20210731213800386.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/image-20210731213800386.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/image-20210731213800386.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/image-20210731213800386.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/image-20210731213800386.png"
        title="image-20210731213800386" /></p>
<p>点击红框中所示按键即可执行。</p>
<p>也可以通过命令执行测试脚本，如下所示：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">flutter test --plain-name &#34;my test&#34; test/widget_test.dart
</code></pre></td></tr></table>
</div>
</div><p>如果想要执行main方法中的所有测试脚本，执行下面脚本：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">flutter test test/widget_test.dart
</code></pre></td></tr></table>
</div>
</div><h3 id="使用说明">使用说明</h3>
<ul>
<li>上面已经说了test()，第一个参数是描述信息，运行时可以通过描述信息执行指定的脚本；第二个参数就是需要执行的方法；此外还有其它可选参数，timeout设置后将替换默认30s的超时时间；skip允许跳过测试（值为String时会打印skip内容）；retry设置重试次数等。</li>
<li>处理test方法外，还有group方法，使用同一个描述信息，用于批量测试脚本执行，如下面代码所示：</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">group(&#34;group test&#34;, (){
    test(&#39;test 1&#39;, (){
      int i = 0;
      expect(i, 0);
    });
    test(&#39;test 2&#39;, (){
      int i = 1;
      expect(i, 1);
    });
  });
</code></pre></td></tr></table>
</div>
</div><p>当然，里面的每个test也可以单独执行。另外，通过描述信息执行测试脚本时，同样的描述信息也会默认分为一个group。</p>
<ul>
<li>上面已经说明了一个简单的expect方法使用，但实际上matcher中还可以支持更复杂的比对效果，例如：</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">test(&#39;complex validations&#39;, (){
    expect(&#34;abc,bcd,efg&#34;, allOf([
      contains(&#34;abc&#34;),
      isNot(startsWith(&#34;bcd&#34;)),
      endsWith(&#34;efg&#34;)
    ]));
  });
</code></pre></td></tr></table>
</div>
</div><ul>
<li>setUp方法与tearDown方法分别在测试脚本执行前和执行后调用，setUp中可以进行一些预处理操作，而tearDown进行一些release操作。例如：</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">group(&#39;setup test&#39;, (){
    File f ;
    setUp(() async {
      f = await new File(&#39;abc.txt&#39;).create();
    });
    
    tearDown(() async {
      await f.delete();
    });
    
    test(&#34;file test&#34;, () async {
      await f.writeAsString(&#39;abc&#39;);
      // 其他操作
    });
  });
</code></pre></td></tr></table>
</div>
</div><ul>
<li>
<p>上面的示例中还使用了async以及await异步操作，在测试脚本中，这些异步操作完成后才会认为测试结束。另外还有一些为异步处理提供的匹配器方法。比如</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">​```dart
test(&#39;async test&#39;, (){
    expect(new Future.value(10), completion(equals(10)));
  });
</code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>异步操作还有<code>expectAsync</code>系列方法，包括<code>expectAsync1、expectAsync2··· expectAsync6</code>，这些方法的区别主要是参数的不同。这个方法有两个作用，方法中有一个参数<code>count</code>，如果方法执行的次数没有达到count数量，会一直等待，测试脚本不会结束；另外如果执行次数超过了count，则会断言失败。下面是一个示例：</p>
</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">test(&#39;expectAsyn&#39;, (){
    var stream = new Stream.fromIterable([1, 2, 3]);

    stream.listen(expectAsync1((number) {
      expect(number, inInclusiveRange(1, 3));
    }, count: 3));
  });
</code></pre></td></tr></table>
</div>
</div><h2 id="组件测试">组件测试</h2>
<p>组件测试可以模拟界面环境，同时模拟一些交互操作，校验反馈结果达到测试效果，需要导入flutter_test库来使用。</p>
<h3 id="使用方法-1">使用方法</h3>
<p>在test的dart文件中import相应的dart文件，下面代码所示就是默认生成的测试文件：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">import &#39;package:flutter/material.dart&#39;;
import &#39;package:flutter_test/flutter_test.dart&#39;;

import &#39;package:flutter_app/main.dart&#39;;

void main() {
  testWidgets(&#39;Counter increments smoke test&#39;, (WidgetTester tester) async {
    // Build our app and trigger a frame.
    await tester.pumpWidget(MyApp());

    // Verify that our counter starts at 0.
    expect(find.text(&#39;0&#39;), findsOneWidget);
    expect(find.text(&#39;1&#39;), findsNothing);

    // Tap the &#39;+&#39; icon and trigger a frame.
    await tester.tap(find.byIcon(Icons.add));
    await tester.pump();

    // Verify that our counter has incremented.
    expect(find.text(&#39;0&#39;), findsNothing);
    expect(find.text(&#39;1&#39;), findsOneWidget);
  });
}
</code></pre></td></tr></table>
</div>
</div><p>相比单元测试来说，测试入口变成了testWidgets，这个方法要求传入的方法对象中必须有WidgetTester类型的参数，除此以外与单元测试的使用方法基本相同。</p>
<p>界面执行方法、脚本执行方法都与单元测试完全一致，因此不再继续说明。</p>
<h3 id="使用说明-1">使用说明</h3>
<p>组件测试中新增WidgetTester对象能够模拟发送点击或滚动的交互事件，再加上在widget树中查找widget的能力。这两个核心功能组成了组件测试需要的界面验证能力。</p>
<p>下面具体说一下WidgetTester常用到的方法：</p>
<ul>
<li><code>Future&lt;void&gt; pumpWidget(Widget widget)</code> 这个方法来导入一个Widget，模拟了一个headless界面。</li>
<li><code>Future&lt;void&gt; tap(Finder finder, {int pointer})</code> 这个方法来触发一个点击事件，点击的位置由Finder确定，在Widget树中找到的一个widget。实际上还有<code>Future&lt;void&gt; tapAt(Offset location, {int pointer})</code>这个方法，在某个具体位置触发一下点击事件。另外还有<code>press、longPress、fling、drag</code>等多种操作，甚至可以自定义手势处理。</li>
<li><code>Future&lt;void&gt; pump()</code> 触发widget更新。交互事件完成后触发界面更新，就可以验证结果是否正确。</li>
</ul>
<h3 id="现有问题">现有问题</h3>
<p>目前Flutter为了保证测试速度，默认HTTP请求的返回值永远都是空的，返回码都是400 - Bad Request。因此涉及到Image.network()，或者类似的其它组件时，会出现问题导致验证过程异常。</p>
<p>这个问题可以通过模拟返回结果的方式来进行规避，但是不是一个最终的解决方案，也无法达到满意的结果。</p>
<h2 id="集成测试">集成测试</h2>
<p>集成测试与单元测试以及组件测试不同，它集成了更多功能，因此这种测试方式需要真实的环境支持，与Android测试使用的Espresso或者UI Automater类似。</p>
<h3 id="导入方式-1">导入方式</h3>
<p>pubspec.yaml 文件中的 <code>dev_dependencies</code>中设置相应依赖：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">dev_dependencies:
  flutter_driver:
      sdk: flutter
</code></pre></td></tr></table>
</div>
</div><h3 id="使用方法-2">使用方法</h3>
<p>我们要使用集成测试，需要做两件事情：</p>
<ul>
<li>创建指令化的应用程序，也就是说可以通过指令方式调用需要展示的应用界面</li>
<li>增加测试项，设置自动交互效果</li>
</ul>
<h4 id="创建指令化的应用程序">创建指令化的应用程序</h4>
<p>指令化应用需要在应用运行前启用<code>Flutter Driver 扩展</code>。也就是说在运行前调用<code>enableFlutterDriverExtension()</code>。该方法执行后调用正常应用的main方法，或者直接runApp方法。如下面示例：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">import &#39;package:flutter_app/main.dart&#39; as mainDart;
import &#39;package:flutter_driver/driver_extension.dart&#39;;

void main() {
  enableFlutterDriverExtension();
  mainDart.main();
}
</code></pre></td></tr></table>
</div>
</div><p>需要注意的是这个dart文件必须放置于<code>test_driver</code>文件夹中，否则命令行执行时有可能找不到可执行文件。现在这个dart文件命名为<code>drive_test.dart</code></p>
<h4 id="增加测试项">增加测试项</h4>
<p>在上面dart文件同级目录下，新增一个文件，注意文件名称必须为<code>指令化文件名称+'_test'</code>，比如这次我就需要命名为<code>drive_test_test.dart</code>。</p>
<p>测试项与之前组件测试、单元测试内容差不多，不过需要注意的是不能直接导入<code>flutter_test</code>库，而导入<code>test</code>库，否则会导致find重复定义的问题。当然导入<code>flutter_test</code>库也可以，需要特殊标明find位置。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">import &#39;package:flutter_driver/flutter_driver.dart&#39;;
//import &#39;package:flutter_test/flutter_test.dart&#39;;
import &#39;package:test/test.dart&#39;;

void main() {

  group(&#39;drive test&#39;, (){
    FlutterDriver driver;

    setUpAll(() async {
      // 连接app
      driver = await FlutterDriver.connect();
    });

    tearDownAll(() async {
      if (driver != null) {
        // 关闭连接
        driver.close();
      }
    });

    test(&#39;add auto test&#39;, () async {
      SerializableFinder icon = find.byType(&#39;Icon&#39;);
        for (int i = 0; i &lt; 5; i++) {
          driver.tap(icon);
          await new Future&lt;Null&gt;.delayed(new Duration(milliseconds: 1000));
        }
      });
    });

  });
}
</code></pre></td></tr></table>
</div>
</div><h4 id="命令行运行">命令行运行</h4>
<p>集成测试不支持Android Studio手工操作，需要通过命令行执行。否则会出现如下错误：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">DriverError: Could not determine URL to connect to application.
</code></pre></td></tr></table>
</div>
</div><p>这是因为界面操作的情况下不是执行<code>flutter driver</code>命令，因此需要手工执行如下命令(前提是手机已经使用USB连接，并启用了USB调试)：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">flutter drive --target=/Users/sunwenwu/project/flutter_app/flutter_app/test_driver/drive_test.dart
</code></pre></td></tr></table>
</div>
</div><p>最终运行结果可以看到，手机上自动打开此应用，每隔1s计数器加1，增加五次以后，应用自动退出。</p>
<h3 id="性能跟踪">性能跟踪</h3>
<p>实际上集成测试除了进行界面自动化测试外，还可以收集测试过程中的性能数据，上面的测试项代码可以写为如下内容：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">test(&#39;add auto test&#39;, () async {
      // 记录闭包中的performance timeline
      Timeline timeline = await driver.traceAction(() async {
        SerializableFinder icon = find.byType(&#39;Icon&#39;);
        for (int i = 0; i &lt; 5; i++) {
          driver.tap(icon);
          await new Future&lt;Null&gt;.delayed(new Duration(milliseconds: 500));
        }
      });

      // The `timeline` object contains all the performance data recorded during
      // the scrolling session. It can be digested into a handful of useful
      // aggregate numbers, such as &#34;average frame build time&#34;.
      TimelineSummary summary = new TimelineSummary.summarize(timeline);
      summary.writeSummaryToFile(&#39;stocks_scroll_perf&#39;, pretty: true);
      summary.writeTimelineToFile(&#39;stocks_scroll_perf&#39;, pretty: true);
    });
</code></pre></td></tr></table>
</div>
</div><p>执行完毕后性能数据写到了<code>stocks_scroll_perf</code>文件中。</p></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>更新于 2021-07-31</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://luckly.work/flutter%E6%B5%8B%E8%AF%95%E8%84%9A%E6%9C%AC%E5%BC%80%E5%8F%91/" data-title="《Flutter测试脚本开发》" data-hashtags="flutter"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://luckly.work/flutter%E6%B5%8B%E8%AF%95%E8%84%9A%E6%9C%AC%E5%BC%80%E5%8F%91/" data-hashtag="flutter"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Hacker News" data-sharer="hackernews" data-url="https://luckly.work/flutter%E6%B5%8B%E8%AF%95%E8%84%9A%E6%9C%AC%E5%BC%80%E5%8F%91/" data-title="《Flutter测试脚本开发》"><i class="fab fa-hacker-news fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://luckly.work/flutter%E6%B5%8B%E8%AF%95%E8%84%9A%E6%9C%AC%E5%BC%80%E5%8F%91/" data-title="《Flutter测试脚本开发》"><i data-svg-src="https://cdn.jsdelivr.net/npm/simple-icons@2.14.0/icons/line.svg"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://luckly.work/flutter%E6%B5%8B%E8%AF%95%E8%84%9A%E6%9C%AC%E5%BC%80%E5%8F%91/" data-title="《Flutter测试脚本开发》" data-image="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"><i class="fab fa-weibo fa-fw"></i></a></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/flutter/">flutter</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">返回</a></span>&nbsp;|&nbsp;<span><a href="/">主页</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/flutter-engine%E6%BA%90%E7%A0%81%E8%B0%83%E8%AF%95/" class="prev" rel="prev" title="《Flutter Engine源码调试》"><i class="fas fa-angle-left fa-fw"></i>《Flutter Engine源码调试》</a>
            <a href="/flutter%E6%B8%B2%E6%9F%93%E5%8E%9F%E7%90%86%E4%B8%8E%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" class="next" rel="next" title="《Flutter渲染原理与性能优化》">《Flutter渲染原理与性能优化》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">早起的年轻人</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank">CC BY-NC 4.0</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.css"><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/autocomplete.js@0.37.1/dist/autocomplete.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/algoliasearch@4.2.0/dist/algoliasearch-lite.umd.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lazysizes@5.2.2/lazysizes.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharer.js@0.4.0/sharer.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":10},"comment":{},"cookieconsent":{"content":{"dismiss":"同意","link":"了解更多","message":"本网站使用 Cookies 来改善您的浏览体验."},"enable":true,"palette":{"button":{"background":"#f0f0f0"},"popup":{"background":"#1aa3ff"}},"theme":"edgeless"},"search":{"algoliaAppID":"PASDMWALPK","algoliaIndex":"index.zh-cn","algoliaSearchKey":"b42948e51daaa93df92381c8e2ac0f93","highlightTag":"em","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":50,"type":"algolia"}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
